/**
 * editor by jxl
 * 基于plupload的阿里云图片上传
 * 参考：http://oss-demo.aliyuncs.com/oss-h5-upload-js-direct/index.html?spm=5176.doc31925.2.2.i6u30f
 *
 * 用法：
 * 1、HTML文件依次引入crypto.js, hmac.js, sha1.js, base64.js, plupload.full.min.js 和该文件
 * 2、var imgs = $("#dom_elem").imgUpload({options}); //dom_elem 为 dom 标签，options 为一些上传选项，如上传的服务器配置等
 * 3、通过 imgs.uploaded 得到所上传的图片数组
 */
(function () {
    var imgupload = {
        init: function (el, option) {
            var base = this;

            base.$elem = $(el).empty();
            base.options = jQuery.extend({}, $.fn.imgUpload.options, base.$elem.data(), option);
            base.uploaded = [];
            base.uuidName = '';

            base.createDom();
        },
        createDom: function () {
            var base = this;

            base.$els = {
                ossfile: $("<div/>", {
                    style: "margin-bottom: 10px;"
                }),
                btn: $("<div/>"),
                btnSelect: $("<a/>", {
                    text: "选择图片",
                    class: "btn btn-info",
                    style: "margin-right: 10px;",
                    href: "javascript: void(0)"
                }),
                btnUpload: $("<a/>", {
                    text: "上传图片",
                    class: "btn btn-info disabled",
                    href: "javascript: void(0)"
                })
            };

            base.$elem.append(base.$els.ossfile).append(base.$els.btn.append(base.$els.btnSelect).append(base.$els.btnUpload));

            base.uploader();
        },
        uploader: function () {
            var base = this;

            var uploader = new plupload.Uploader({
                runtimes: base.options.plupload.runtimes,
                browse_button: base.$els.btnSelect[0],
                multi_selection: base.options.plupload.multi_selection,
                container: base.$elem[0],
                flash_swf_url: base.options.plupload.flash_swf_url,
                silverlight_xap_url: base.options.plupload.silverlight_xap_url,
                url: base.options.oss.url,

                init: {
                    PostInit: function () {
                        base.$els.ossfile.empty();
                        base.uploaded = [];
                        base.$els.btnUpload.on("click", function () {
                            base.upStart(uploader, '', false);
                            return false;
                        });
                    },

                    FilesAdded: function (up, files) {
                        plupload.each(files, function (file) {
                            base.previewImage(file, function (imgsrc) {
                                base.$els.ossfile.append('<div style="position: relative; margin-bottom: 5px;">'
                                    + '<div style="position:absolute; top: 0;left: 0;"><img src="' + imgsrc + '" name="' + file.name + '" width="60", height="60"></div>'
                                    + '<div id="' + file.id + '" style="width: 100%; padding-left: 70px; padding-right: 20px; min-height: 60px;">' + file.name + ' (' + plupload.formatSize(file.size) + ')'
                                    + '<p class="text-muted" style="margin: 0; font-size: 12px;"></p>'
                                    + '<div class="progress" style="margin: 0;"><div class="progress-bar" style="width: 0%"></div></div></div>'
                                    + '<div style="position: absolute; top: 20px; right: 3px;"><a href="javascript:void(0);" class="img-delete" data-file-id="'+ file.id +'">&times;</a></div>'
                                    + '</div>');

                                base.removeFile(up);
                            });
                        });
                        base.$els.btnUpload.removeClass("disabled");
                    },

                    BeforeUpload: function (up, file) {
                        base.upStart(up, file, true);
                    },

                    UploadProgress: function (up, file) {
                        var d = document.getElementById(file.id);
                        d.getElementsByTagName('p')[0].innerHTML = '<span>' + file.percent + "%</span>";
                        var prog = d.getElementsByTagName('div')[0];
                        var progBar = prog.getElementsByTagName('div')[0]
                        progBar.style.width = file.percent + '%';
                        progBar.setAttribute('aria-valuenow', file.percent);
                    },

                    FileUploaded: function (up, file, info) {
                        if (info.status == 200) {
                            document.getElementById(file.id).getElementsByTagName('p')[0].innerHTML =
                                '上传成功，上传文件名：' + base.uuidName + ".jpg";

                            $("#" + file.id).parent().css("background-color", "#f0fffa");
                        }
                        else {
                            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = info.response;
                        }
                    },

                    Error: function (up, err) {
                        document.getElementById('console').appendChild(document.createTextNode("\nError xml:" + err.response));
                    }
                }
            });

            uploader.init();

            base.plupload = uploader;
        },
        removeFile: function (up) {
            var base = this;
            var els = $(".img-delete");
            els.on("click", function (e) {
                var el = $(e.target);
                el.parent().parent().remove();
                //var toremove = '';
                var id = el.attr("data-file-id");

                var file = up.getFile(id);
                if(file.percent == 100) {
                    for (var i in base.uploaded) {
                        if(base.uploaded[i].indexOf(file.uuid) > -1) {
                            base.uploaded.splice(i, 1);
                        }
                    }
                }
                up.removeFile(id);

               /* for (var i in up.files) {
                    if (up.files[i].id === id) {
                        toremove = i;
                    }
                }
                up.files.splice(toremove, 1);*/
            });
        },
        upStart: function (up, file, ret) {
            var base = this;

            var filename = file.name;
            var extend = "";

            if (typeof filename != "undefined" && filename != '') {
                extend = "." + filename.replace(/.+\./, "");
                base.uuidName = base.getUuid();
                base.uploaded.push(base.options.oss.url + "/" + base.options.dir + "/" + base.uuidName + extend);
                file.uuid = base.uuidName;
            }
            new_multipart_params = {
                'key': base.options.dir + "/" + base.uuidName + extend,
                'policy': base.getBase64(),
                'OSSAccessKeyId': base.options.oss.accessKeyId,
                'success_action_status': '200',
                'signature': base.getSign()
            };

            up.setOption({
                'url': base.options.oss.url,
                'multipart_params': new_multipart_params
            });

            up.start();
        },
        getBase64: function () {
            return Base64.encode(JSON.stringify({
                "expiration": "2020-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
                "conditions": [
                    ["content-length-range", 0, 2048000] // 设置上传文件的大小限制
                ]
            }));
        },
        getSign: function () {
            var base = this;
            var bytes = Crypto.HMAC(Crypto.SHA1, base.getBase64(), base.options.oss.accessKeySecret, {asBytes: true});
            return Crypto.util.bytesToBase64(bytes);
        },
        getUuid: function () {
            var len = 32;//32长度
            var radix = 16;//16进制
            var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
            var uuid = [], i;
            radix = radix || chars.length;
            if (len) {
                for (i = 0; i < len; i++)uuid[i] = chars[0 | Math.random() * radix];
            } else {
                var r;
                uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
                uuid[14] = '4';
                for (i = 0; i < 36; i++) {
                    if (!uuid[i]) {
                        r = 0 | Math.random() * 16;
                        uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                    }
                }
            }
            return uuid.join('');
        },
        previewImage: function (file, callback) {
            if (!file || !/image\//.test(file.type)) return;
            if (file.type == 'image/gif') {
                var fr = new mOxie.FileReader();
                fr.onload = function () {
                    callback(fr.result);
                    fr.destroy();
                    fr = null;
                };
                fr.readAsDataURL(file.getSource());
            } else {
                var preloader = new mOxie.Image();
                preloader.onload = function () {
                    //preloader.downsize(300, 300);//压缩要预览的图片,宽300，高300
                    var imgsrc = preloader.type == 'image/jpeg' ? preloader.getAsDataURL('image/jpeg', 80) : preloader.getAsDataURL();
                    callback && callback(imgsrc);
                    preloader.destroy();
                    preloader = null;
                };
                preloader.load(file.getSource());
            }
        }
    };

    $.fn.imgUpload = function (option) {
        var obj = Object.create(imgupload);
        this.each(function () {
            obj.init(this, option);
        });
        return obj;
    };

    $.fn.imgUpload.options = {
        oss: {
            region: 'oss-cn-shenzhen',
            accessKeyId: 'LTAImVBCIWgaWXav',
            accessKeySecret: 'DWYPPxaxgvGm30yFn0BYB8ABRJjDKL',
            bucket: 'vimi8-dev',
            url: 'http://vimi8-dev.oss-cn-shenzhen.aliyuncs.com'
        },
        dir: "imgupload",
        plupload: {
            runtimes: 'html5,flash,silverlight,html4',
            multi_selection: true,
            flash_swf_url: 'lib/plupload-2.1.2/js/Moxie.swf',
            silverlight_xap_url: 'lib/plupload-2.1.2/js/Moxie.xap'
        }
    }
})(jQuery);